﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace DDD4Fun.Common
{
    public class CCopy
    {
        public  static void TestCopy()
        {
            CCopyPerson p1 = new CCopyPerson()
            {
                FirstName = "jimmy",
                LastName = "lee",
                CCopyDepartment = new CCopyDepartment() {  DName = "d1"}
            };
            CCopyPerson p2 = p1.ShallowClone() as CCopyPerson;
            Console.WriteLine(string.Format("{0} {1}:{2}", p1.FirstName, p1.LastName,p1.CCopyDepartment.DName));
            p2.CCopyDepartment.DName = "d2";
            Console.WriteLine(string.Format("{0} {1}:{2}", p1.FirstName, p1.LastName, p1.CCopyDepartment.DName));

            CCopyPerson p3 = p1.DeepClone() as CCopyPerson;
            Console.WriteLine(string.Format("{0} {1}:{2}", p1.FirstName, p1.LastName, p1.CCopyDepartment.DName));
            p3.CCopyDepartment.DName = "d3";
            Console.WriteLine(string.Format("{0} {1}:{2}", p1.FirstName, p1.LastName, p1.CCopyDepartment.DName));

        }
    }

    [Serializable]//深拷贝必须属性
    class CCopyPerson:ICloneable
    {
        public string IDCode { set; get; }

        public string FirstName { set; get; }

        public string LastName { set; get; }

        public CCopyDepartment CCopyDepartment { set; get; }

        #region ICloneable Members

        public object Clone()
        {
            //浅拷贝
            return this.MemberwiseClone();
        }

        #endregion

        public CCopyPerson DeepClone()
        {
            //深拷贝
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();//序列化多个遵循堆栈的顺序
                formatter.Serialize(objectStream, this);
                objectStream.Seek(0, SeekOrigin.Begin);
                return formatter.Deserialize(objectStream) as CCopyPerson;
            }
        }

        public CCopyPerson ShallowClone()
        {

            return Clone() as CCopyPerson;
        }
    }

    [Serializable]
    class CCopyDepartment
    {
        public string DName { get; set; }
    }
}
